package com.wencai.util;

import com.wencai.bean.StockInDate;
import com.wencai.bean.StockTimes;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wangpan
 * @date 2022/10/26
 */
public class StockUtil {
    public static final List<StockInDate> readStockFromFile(String path) throws IOException {
        File f = new File(path);
        BufferedReader reader = new BufferedReader(new FileReader(f));
        String line;
        List<String> lines = new ArrayList<>();
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        String[] split = lines.get(0).split("\t");
        List<StockInDate> stocks = new ArrayList<>();
        for (String date : split) {
            StockInDate stockInDate = new StockInDate();
            stockInDate.setDate(date);
            stocks.add(stockInDate);
        }
        for (int i = 1; i < lines.size(); i++) {
            String[] s = lines.get(i).split("\t");
            for (int j = 0; j < s.length; j++) {
                StockInDate stockInDate = stocks.get(j);
                stockInDate.getStocks().add(s[j]);
            }
        }
        for (StockInDate stockInDate : stocks) {
            List<String> stocks1 = stockInDate.getStocks();
            List<String> collect = stocks1.stream().filter(item -> !item.isEmpty()).collect(Collectors.toList());
            stockInDate.setStocks(collect);
        }
        return stocks;
    }

    public static List<StockTimes> getStockTimes(List<StockInDate> stockInDates) {
        List<String> lists = new ArrayList<>();
        for (StockInDate stockInDate : stockInDates) {
            lists.addAll(stockInDate.getStocks());
        }
        List<StockTimes> stockTimes = new ArrayList<>();
        Set<String> consumed = new HashSet<>();
        for (String str : lists) {
            if (consumed.contains(str)) {
                StockTimes stockTimes1 = stockTimes.stream().filter(item -> item.getStock().equals(str)).findFirst().get();
                stockTimes1.setCount(stockTimes1.getCount() + 1);
            } else {
                consumed.add(str);
                StockTimes stockTime1 = new StockTimes();
                stockTime1.setCount(1);
                stockTime1.setStock(str);
                stockTimes.add(stockTime1);
            }
        }
        stockTimes.sort((item1, item2) -> item2.getCount() - item1.getCount());
        return stockTimes;
    }
}
